//
//  WBOAuthViewController.swift
//  weibo
//
//  Created by yanghong on 15/12/7.
//  Copyright © 2015年 杨鸿. All rights reserved.
//

import UIKit
import SVProgressHUD
let APPKEY = "522856460"
let APP_SECRET = "22c5fca7c351723d2d172dbfe63fb653"
let REDIRECT_URI = "http://www.itheima.com/"

// https://api.weibo.com/oauth2/authorize (OAuth2的authorize接口URL)

class WBOAuthViewController: UIViewController, UIWebViewDelegate {
    
    lazy var webView: UIWebView = {
    
    let webView = UIWebView()
        
        return webView
    
    }()
    
    override func loadView() {
        
        view = webView
    }
    
    override func viewDidLoad() {
        
        webView.delegate = self
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        setupUI()
    }
    
    private func setupUI() {
    
    navigationItem.leftBarButtonItem = UIBarButtonItem( title: "取消", target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem( title: "自动填充", target: self, action: "autoFill")
    
       navigationItem.title = "微博登录"
    }
    
    func dismiss() {
        
        SVProgressHUD.dismiss()
  
        navigationController?.dismissViewControllerAnimated(true, completion: nil)

    }
    
    func autoFill() {
        
        let jsString = "document.getElementById('userId').value='18702324766';document.getElementById('passwd').value='123456'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    
      print("fill userN and passW")
    
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
     SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
      SVProgressHUD.dismiss()
    }
    // MARK -  webView将要加载某个请求时,会调用这个方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        guard let url = request.URL?.absoluteString else {
         
        return true
        }
        
        if !url.hasPrefix(REDIRECT_URI) {
        
            return true
        
        }
        
        print(request.URL!.query)
        
        if request.URL!.query!.hasPrefix("code=") {
        
        let code = request.URL!.query!.substringFromIndex("code=".endIndex)
        
        WBUserAccountViewModel.sharedAccount.loadAccessToken(code, complet:  { (isSuccessed) -> () in
            if !isSuccessed {
            
                print("加载失败")
                SVProgressHUD.showErrorWithStatus("加载失败")
                return
            
            }
            
            print("登录成功")
            //走到这里,表示加载成功
            SVProgressHUD.dismiss()
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
              NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: self)
            })
            
            
        })
            
        }else{
        
            dismiss()
        
        }
       
      return false
    }
    
    

}
